package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**自定义实现删除功能：逻辑如下，删除时判断是否当前业务是否关联了菜品和套餐，如果关联之后抛出业务异常，两个都不关联则删除成功
 * @author tongchen
 * @create 2023-01-25 17:08
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>implements CategoryService  {
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    DishMapper dishMapper;
    @Autowired
    SetmealMapper setmealMapper;

    @Override
    public R<String> delete(Long ids) {
        //判断是否关联了菜品
        LambdaQueryWrapper<Dish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Dish::getCategoryId, ids);
        Integer count1 = dishMapper.selectCount(queryWrapper1);
        if(count1>0){
            throw new CustomerException("该类中关联了菜品，无法删除");
        }
        //判断是否关联了套餐
        LambdaQueryWrapper<Setmeal> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Setmeal::getCategoryId,ids );
        Integer count = setmealMapper.selectCount(queryWrapper2);
        if(count>0){
            throw new CustomerException("该类中关联了套餐，无法删除");
        }
        //都没有关联则进行删除操作
        categoryMapper.deleteById(ids);
        return  R.success("删除成功");
    }
}
